package com.dyava.commons.codec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;


public class DesCodec {
	   /**
     * AES java-javascript 只支持部填充摸索
     */
    public static final String format = "DES/ECB/PKCS5PADDING";
    /**
     * DES 加密key，8位
     */
    public String key = "96497274";
    /**
     * DES 偏移量，8位
     */
//    public static String iv = "12345678";

    SecretKeySpec keyspecDes;

    public DesCodec(String key) {
        this.key = key;
        try {
            keyspecDes = new SecretKeySpec(key.getBytes("utf-8"), "DES");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用AES加密
     * @since 0.0.11
     */
    public String encrypt(String data){
        if(StringUtils.isEmpty(data)){
            return null;
        }
        try {
            byte[] encrypted = encrypt(data.getBytes("utf-8"));
            return Base64.encodeBase64String(encrypted);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用AES加密
     * @since 0.0.11
     */
    public byte[] encrypt(byte[] dataBytes){
        if(dataBytes==null){
            return null;
        }
        try {
            Cipher cipher = Cipher.getInstance(format);
            int blockSize = cipher.getBlockSize();

//            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes("utf-8"));

            cipher.init(Cipher.ENCRYPT_MODE, keyspecDes);
            byte[] encrypted = cipher.doFinal(dataBytes);

            return encrypted;

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用DES解密
     * @since 0.0.11
     */
    public String decrypt(String data){
        if(StringUtils.isEmpty(data)){
            return null;
        }
        try
        {
            byte[] original = decrypt(Base64.decodeBase64(data));
            String originalString = new String(original,"utf-8");
            return originalString;
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 使用DES解密
     * @since 0.0.11
     */
    public byte[] decrypt(byte[] encrypted){
        if(encrypted==null){
            return null;
        }
        try
        {
            Cipher cipher = Cipher.getInstance(format);
//            IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keyspecDes);
            return cipher.doFinal(encrypted);
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
